#include "stdafx.h"
#include "Texton.h"

bool Texton::IsSimilar(Texton* _texton) const
{
	// Check that both textons have images of the same size
	if (!m_pTextonImage || !_texton->m_pTextonImage 
		|| m_pTextonImage->height != _texton->m_pTextonImage->height
		|| m_pTextonImage->width != _texton->m_pTextonImage->width)
	{
		return false;
	}

	// Use OpenCV matching functions

	//specify the size needed by the match function
	int resultW = m_pTextonImage->width - _texton->m_pTextonImage->width + 1;
	int resultH = m_pTextonImage->height - _texton->m_pTextonImage->height +1;

	//create each of the result images
	IplImage* result0 = cvCreateImage(cvSize(resultW, resultH), IPL_DEPTH_32F, 1);
	IplImage* result1 = cvCreateImage(cvSize(resultW, resultH), IPL_DEPTH_32F, 1);
	IplImage* result2 = cvCreateImage(cvSize(resultW, resultH), IPL_DEPTH_32F, 1);
	IplImage* result3 = cvCreateImage(cvSize(resultW, resultH), IPL_DEPTH_32F, 1);
	IplImage* result4 = cvCreateImage(cvSize(resultW, resultH), IPL_DEPTH_32F, 1);
	IplImage* result5 = cvCreateImage(cvSize(resultW, resultH), IPL_DEPTH_32F, 1);
		
	//apply each of the matching techniques
	cvMatchTemplate(m_pTextonImage, _texton->m_pTextonImage, result0, CV_TM_SQDIFF);
	cvMatchTemplate(m_pTextonImage, _texton->m_pTextonImage, result1, CV_TM_SQDIFF_NORMED);
	cvMatchTemplate(m_pTextonImage, _texton->m_pTextonImage, result2, CV_TM_CCORR);
	cvMatchTemplate(m_pTextonImage, _texton->m_pTextonImage, result3, CV_TM_CCORR_NORMED);
	cvMatchTemplate(m_pTextonImage, _texton->m_pTextonImage, result4, CV_TM_CCOEFF);
	cvMatchTemplate(m_pTextonImage, _texton->m_pTextonImage, result5, CV_TM_CCOEFF_NORMED); 

	/*
	cvNamedWindow( "SQDIFF", 0 );
    cvShowImage(   "SQDIFF", result0 );
    cvNamedWindow( "SQDIFF_NORMED", 0 );
    cvShowImage(   "SQDIFF_NORMED", result1 );
    cvNamedWindow( "CCORR", 0 );
    cvShowImage(   "CCORR", result2 );

    cvNamedWindow( "CCORR_NORMED", 0 );
    cvShowImage(   "CCORR_NORMED", result3 );

    cvNamedWindow( "CCOEFF", 0 );
    cvShowImage(   "CCOEFF", result4 );

    cvNamedWindow( "CCOEFF_NORMED", 0 );
    cvShowImage(   "CCOEFF_NORMED", result5 );
    cvWaitKey(0);
	*/

	// check results

	return true;

	/*

	// Scan over the image and compare each pixel
	for(int x=0; x < m_pTextonImage->width; x++) {
		for(int y=0; y < m_pTextonImage->height; y++) {

			// Get pixel value from the input image
			int inputVal = (int)(cvGet2D(inputImage,yOffset + y, xOffset + x).val[0]);
			// Get pixel value from detector
			int detectorVal = (int)(cvGet2D(detectorImage,y,x).val[0]);

			int diff = inputVal-detectorVal;
			int sqDiff = POW2(diff);
			sum += sqDiff;
		}
	}
	*/
}

void Texton::MarkTexton(IplImage* inputImage, CvScalar color)
{
	cvDrawRect(inputImage, cvPoint(x,y),cvPoint(x + width,y + height), color);
}

